﻿using System;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    [Description("展示对话界面")]
    public class ShowDialogue : CallableActionNodeBase
    {
        private int currentId;

        [HideInInspector] public FlowOutput onComplete;

        public static Action<int> OnDialogueComplete;

        public void Invoke(int dialogueId, int dialogueChildId, bool autoClose, float autoCloseTime)
        {
            var p = LibertyAIUtils.GetPlayerEntity();
            if (p) p.data.invincible = true;
            
            BlueprintUtils.ShowDialoguePanel(dialogueId, dialogueChildId, parentNode, autoClose, autoCloseTime );
            OnDialogueComplete += DialogueComplete;
        }

        private void DialogueComplete(int id)
        {
            if (currentId == id)
            {
                onComplete?.Call(new Flow());
                var p = LibertyAIUtils.GetPlayerEntity();
                if (p) p.data.invincible = false;
            }
        }

        protected override void OnRegisterPorts(FlowNode node)
        {
            var p1 = node.AddValueInput<int>("dialogueId");
            var p2 = node.AddValueInput<int>("dialogueChildId");
            var p3 = node.AddValueInput<bool>("autoClose");
            var p4 = node.AddValueInput<float>("autoCloseTime");

            var o = node.AddFlowOutput("Out");
            node.AddFlowInput("In", (Flow f) =>
            {
                currentId = p1.value;
                Invoke(p1.value, p2.value, p3.value, p4.value);
                o.Call(f);
            });

            onComplete = node.AddFlowOutput("onComplete");
        }

        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            OnDialogueComplete -= DialogueComplete;
            var p = LibertyAIUtils.GetPlayerEntity();
            if (p) p.data.invincible = true;
        }
    }
}